/*
 * It will initialize the links that charges the section contents in the sections containers (blocks)
 * It has the optional argument myObject. my
If this argument is set it will initialize only the links that are relative (have the container target)
 * to the myFor container specified. Or it can be a link object so in that case it will initialize just that link.
 */
function initLoadingElements(myObject) {
	//Elements will contain a list of tags candidates to perform the loading facility
	var elements=[];
	
	if (typeof myObject == "object") {
		elements=[myObject];
	}
	//In case it is not an object it will be the id path name of the block that will contain the elements to be initiated to the loading facility
	else {
		var myFor;
		if (myObject) {
			myFor=myObject;
			if (myFor.indexOf(":")>-1) {
				myFor=myFor.substring(myFor.lastIndexOf(":")+1)
			}
		}
		var myDocument;
		if (myFor) myDocument=document.getElementById(myFor);
		else myDocument=document;
		
		var aTags=myDocument.getElementsByTagName("a");
		var aElements=[];
		for (var i=0;i<aTags.length;i++) {
			if (aTags[i].getAttribute("myFor")) aElements.push(aTags[i]);
		}
		var buttonTags=myDocument.getElementsByTagName("input");
		var buttonElements=[];
		for (var i=0;i<buttonTags.length;i++) {
			if (buttonTags[i].type=="button" && buttonTags[i].getAttribute("myFor")) buttonElements.push(buttonTags[i]);
		}
		var formTags=myDocument.getElementsByTagName("form");
		var formElements=[];
		for (var i=0;i<formTags.length;i++) {
			if (formTags[i].getAttribute("myFor")) formElements.push(formTags[i]);
		}
		var selectTags=myDocument.getElementsByTagName("select");
		var selectElements=[];
		for (var i=0;i<selectTags.length;i++) {
			if (selectTags[i].getAttribute("myFor")) selectElements.push(selectTags[i]);
		}
		
		elements=aElements.concat(buttonElements);
		elements=elements.concat(formElements);
		elements=elements.concat(selectElements);
	}
	
	for (var i=0;i<elements.length;i++) {
		//we attach the function and make it the default click performance
		elements[i].request=request;
		if (elements[i].tagName!="FORM") elements[i].activate=activate;
		
		if (elements[i].tagName=="FORM") {
			elements[i].validateData=validateData;
			elements[i].onsubmit= function () {
				if ( this.validateData()) {
					return this.request();
				}
				return false;
			}
		}
		else if (elements[i].tagName=="SELECT") {
			elements[i].onchange= function () {
				this.href=this.getAttribute("href") + this.options[this.selectedIndex].value;
				this.request();
			}
		}
		else elements[i].onclick= function () {
			this.activate();
			return this.request();
		}
	}
	
	/*
	 * This is a function that checks that the form data has fulfilled the specification before send it.
	 * It is restricted to the form
	 */
	function validateData() {
		
		for (var i=0; i<this.elements.length; i++) {
			this.elements[i].validateTerms = validateTerms;
			this.elements[i].validateTerms();
		}

		for (var i=0; i<this.elements.length; i++) {
			if (this.elements[i].className.indexOf("invalid")>-1) {
				this.elements[i].focus();
				return false;
			}
		}
		return true;
		
		/*
		 * This is a function restricted to a form element that checks if the form Element value fulfil the terms
		 */
		function validateTerms(){
			this.validateTerm=validateTerm;
			var myExpecteds=new Array();
			if (this.getAttribute("myExpected")) myExpecteds=this.getAttribute("myExpected").split(" ");
			for (var i=0;i<myExpecteds.length;i++) {
				var resultClass=this.validateTerm(myExpecteds[i]);
				if (resultClass) this.className=resultClass;
				else this.className="";
			}

			/*
			 * This is a function restricted to a form element and it checks if its value fulfil the term specified
			 */
			function validateTerm(myTerm){
				var resultClass;
				if (myTerm.indexOf("number")>-1) {
					var number="";
					for(var i=0;i<this.value.length;i++){
						if (("0123456789").indexOf(this.value.charAt(i)) > -1) number+=this.value.charAt(i);
					}
					this.value=number;
				}
				else if (myTerm.indexOf("rqd")>-1) {
					if (!this.value) resultClass = "invalid ";
				}
				else if (myTerm.indexOf("checked")>-1) {
					if (!this.checked) resultClass = "invalid ";
				}
				return resultClass;
			}
		}
	}
	function activate() {
		var myHref;
		if  (this.href) {
			myHref=this.href;
		}
		else {
			return false;
		}
		var myFor=this.getAttribute("myFor");
		if (myFor.indexOf(":")>-1) {
			myFor=myFor.substring(myFor.lastIndexOf(":")+1)
		}
		var aTags=document.getElementsByTagName('a');
		for (var i=0;i<aTags.length;i++) {
			var myElementFor=aTags.item(i).getAttribute("myFor");
			if (myElementFor){
				if (myElementFor.indexOf(":")>-1) {
					myElementFor=myElementFor.substring(myElementFor.lastIndexOf(":")+1)
				}
				if (myElementFor==myFor) {
					if (aTags.item(i).className.search(/selected/)>-1) {
						aTags.item(i).className=aTags.item(i).className.replace(/selected/g,'');
					}
					if (aTags.item(i).href==myHref) aTags.item(i).className+=" selected";
				}
			}
		}
	}

	function request() {
		//If href is undefined the request will perform the block removal.
		if (!this.href && this.tagName!="FORM") {
			document.body.removeChild(document.getElementById(this.getAttribute("myFor")));
			return false;
		}
		//We find the end node of the path name for the block id. This is for the optional block_id notation like block_id:sub_block_id.
		var myFor=this.getAttribute("myFor");
		if (myFor.indexOf(":")>-1) {
			myFor=myFor.substring(myFor.lastIndexOf(":")+1)
		}
		//We create a new element when there is no element with an id equal to myFor
		if (!document.getElementById(myFor)) {
			var divElement=document.createElement("div");
			divElement.id=myFor;
			document.body.appendChild(divElement);
		}
		
		var xmlhttp=new XMLHttpRequest();
		xmlhttp.onload=reqListener;
		xmlhttp.myBlock=document.getElementById(myFor);
		xmlhttp.myBlock.innerHTML ="Loading...";
		xmlhttp.myBlock.oldClassName=xmlhttp.myBlock.className;
		xmlhttp.myBlock.className+=" ajaxLoading";
		
		if (this.tagName=="FORM") {
			xmlhttp.open("POST",this.action,true);
			xmlhttp.send(new FormData(this));
		}
		else {
			xmlhttp.open("GET",this.href,true);
			xmlhttp.send();
		}
		
		return false;
		
		function reqListener() {
			this.myBlock.className=this.myBlock.className.replace(/ajaxLoading/gi,'');
			//this.myBlock.className="";
			this.myBlock.innerHTML = this.responseText;
			initLoadingElements(this.myBlock.id);
			// The javascript at the loaded file is not executed due xmlhttp specification.
			// We execute the script through eval function
			var scriptElements = this.myBlock.getElementsByTagName("script");
			for (var i=0; i< scriptElements.length; i++) {
				eval(scriptElements[i].innerHTML);
			}
		}
	}
}

/*
 * This function stablish at the container rel in path format to the contient href in short format and performs the correspondent actions that are
 * required when a new section is loaded
 */
function setViewTo(href, myFor) {
	// We load the xml http requests
	var myATag=document.createElement("a");
	myATag.href=href;
	myATag.setAttribute("myFor",myFor);
	initLoadingElements(myATag);
	document.myLoader=myATag;
	if (document.readyState == "complete") {
		document.myLoader.activate();
		document.myLoader.request();
	}
		
	else {
		document.onreadystatechange = function () {
			if (document.readyState == "complete") {
				document.myLoader.activate();
				document.myLoader.request();
			}
		}
	}
}
